package com.ly.common.core.tool.security.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ly.common.core.bean.R;
import com.ly.common.core.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 访问未授权的资源-403
 *
 * @author Zheng Jie
 */
@Slf4j
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        // 当用户在没有授权的情况下访问受保护的REST资源时，将调用此方法发送403 Forbidden响应
        int code = HttpStatus.UNAUTHORIZED.value();
        String uri = request.getRequestURI();
        String msg = StrUtil.format("请求访问：{}，禁止访问，您没有权限访问此资源源", uri);
        log.error("禁止访问，您没有权限访问此资源,uri为:{}", uri);
        ServletUtils.renderString(response, JSONUtil.toJsonStr(R.fail(code, msg)));
    }
}
